﻿@using viBook.Common
@using viBook.Helpers
@using viBook.Models
@model Chapter
@{
    var totalCommentPage = (int)Math.Ceiling((double)Model.NumberOfComments / Constant.MaximunCommentPerChapter);
    if (totalCommentPage == 0)
    {
        totalCommentPage = 1;
    }
    bool isShowNextButton = totalCommentPage > 1;
}
<script type="text/javascript">
var numberOfDeletedPages = 0;
$(window).scroll(function(){
         if  ($(document).height() - $(window).height()- $(window).scrollTop() <= 200){
             var startIndex = viewmodel.pictureCollection().length;
             startIndex += numberOfDeletedPages;
             var nextPicture = $(pictureList).slice(startIndex, startIndex+1)[0];
             if(nextPicture !== undefined)
             viewmodel.pictureCollection.push(nextPicture);
         }
 });
function Comment(id, username, userImage, content, createdDate, numberOfLike , isLiked, isReported,isAuthorized) {
    return {
        id: ko.observable(id),
        username: ko.observable(username),
        content: ko.observable(content),
        createdDate: ko.observable(createdDate),
        userImage: ko.observable(userImage),
        numberOfLike : ko.observable(numberOfLike ),
        chapterId: ko.observable( @Model.Id ),
        isLiked: ko.observable(isLiked),
        isReported:ko.observable(isReported),
        isAuthorized:ko.observable(isAuthorized),
        deleteFunc: function() {
                     var currentTag = this;
                      var answer = confirm("Do you want to delete this comment?");
                     if (answer) {
                         $.ajax({
                                 url: '@Url.Action("Delete", "ChapterComments")',
                                 type: 'POST',
                                 data: ko.toJSON({ id: this.id }),
                                 contentType: 'APPLICATION/JSON',
                                 success: function(result) {
                                     if (result.success) {
                                         viewmodel.commentCollection.remove(currentTag);
                                         viewmodel.numberOfComments(viewmodel.numberOfComments() - 1);
                                     }
                                 }
                             });}
                 },
        likeFunc: function() {
            var currentComment = this;
            if (!currentComment.isLiked()) {
                $.ajax({
                        url: '@Url.Action("Like", "ChapterComments")',
                        type: 'POST',
                        data: ko.toJSON({ id: this.id }),
                        contentType: 'APPLICATION/JSON',
                        success: function(result) {
                            if (result.success) {
                                if(currentComment.isLiked()) {
                                     currentComment.numberOfLike(currentComment.numberOfLike() - 1);
                                 }
                                 else {
                                     currentComment.numberOfLike(currentComment.numberOfLike() + 1);
                                 }
                                 currentComment.isLiked(!currentComment.isLiked());
                                
                            } else {
                                window.ShowError(result.message);
                            }
                        }
                    });
            } else {
                $.ajax({
                        url: '@Url.Action("UnLike", "ChapterComments")',
                        type: 'POST',
                        data: ko.toJSON({ id: this.id }),
                        contentType: 'APPLICATION/JSON',
                        success: function(result) {
                            if (result.success) {
                                     if(currentComment.isLiked()) {
                                     currentComment.numberOfLike(currentComment.numberOfLike() - 1);
                                 }
                                 else {
                                     currentComment.numberOfLike(currentComment.numberOfLike() + 1);
                                 }
                                 currentComment.isLiked(!currentComment.isLiked());
                            } else {
                                window.ShowError(result.message);
                            }
                        }
                    });
            }
        },
        reportComment : function() {
             var answer = confirm("Do you want to report this comment?");
                     if (answer) {
                         var currentComment = this;
                         $.ajax({
                                 url: '@Url.Action("ReportComment", "ChapterComments")',
                                 type: 'POST',
                                 data: ko.toJSON({ id: this.id }),
                                 contentType: 'APPLICATION/JSON',
                                 success: function(result) {
                                     if (result.success) {
                                         currentComment.isReported(true);
                                     } else {
                                         alert(result.message);
                                     }
                                 }
                             });}
        }
    };
}

function Picture(id, src, tagCollection) {
    return {
        id: id,
        src: ko.observable(src),
        tagCollection: ko.observableArray(tagCollection),
        onRenderTagCompleted: function(element) {
            var tagIndicator = $(element)[1];
            var contentDiv = $(element)[4];
            $(tagIndicator).fitText(0.5);
            $(contentDiv).fitText(0.5);
            $(tagIndicator).ready(function() {
                $(tagIndicator).hover(
                    function() {
                        $(contentDiv).toggle();
                    });
            });
        },
        deletePage: function () {
            var answer = confirm("Do you want to delete this page?");
                     if (answer) {
                              var curentPage = this;
                         $.ajax({
                                 url: '@Url.Action("Delete", "Pages")',
                                 type: "POST",
                                 data: JSON.stringify({ id: this.id }),
                                 dataType: "JSON",
                                 contentType: "APPLICATION/JSON; CHARSET=UTF-8",
                                 complete: function() {
                                     viewmodel.pictureCollection.remove(curentPage);
                                     numberOfDeletedPages++;
                                 },
                                 error: function() {
                                     alert("error");
                                 }
                             });
                     }
        }
    };
}

function Tag(positionStr, content) {
    var temp = positionStr.split("_");
    var x = parseInt(temp[0]);
    var y = parseInt(temp[1]);
    var w = parseInt(temp[2]);
    var h = parseInt(temp[3]);
    return {
        x: ko.observable(x + 'px'),
        y: ko.observable(y + 'px'),
        x2: ko.observable((x + w) + 'px'),
        w: ko.observable(w + 'px'),
        h: ko.observable(h + 'px'),
        content: ko.observable(content)
    };
}

function ContentTag(id, name, numberOfBooks) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        numberOfBooks: ko.observable(numberOfBooks)
    };
}

function TagMode(desc, value) {
    return {
        desc: ko.observable(desc),
        value: ko.observable(value)
    };
}

var chapterId = @Model.Id ,
    commentList = @CustomHelpers.ChapterCommentsToJavaScriptConverter(@Model.Comments.ToList()) ,
    pictureList = @CustomHelpers.PagesToJavaScriptConverter(@Model.Pages.ToList()) ,
    contentTagList = @CustomHelpers.ContentTagsToJavaScriptConverter(@Model.Book.ContentTags.ToList()) ,
    availableTagModes = [new TagMode("Normal", "TagTemplate"), new TagMode("Hover", "TagTemplateHover"), new TagMode("Disable", "TagTemplateDisable")],
    viewmodel = {
        commentCollection: ko.observableArray(commentList),
        comment: ko.observable(new Comment()),
        commentPageNo: ko.observable(1),
        totalCommentPage: ko.observable( @totalCommentPage ),
        isShowPrevBtn: ko.observable(false),
        isShowNextBtn: ko.observable( @isShowNextButton.BooleanToJavascript() ),
        numberOfComments: ko.observable( @Model.NumberOfComments ),
        isLiked: ko.observable( @Model.IsLiked.BooleanToJavascript() ),
        onRenderCommentCompleted: function (element) {
            $(element).hover(
                function() { $(element).find('#closeButton').show(); },
                function() { $(element).find('#closeButton').hide(); });
        },
        onRenderImageCompleted : function(item) { },
        fetchNextCommentPage: function() {
            $.ajax({
                    url: '@Url.Action("FetchNextCommentPage", "ChapterComments")',
                    type: 'POST',
                    data: ko.toJSON({ chapterId: chapterId, pageNumber: viewmodel.commentPageNo() + 1 }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.isSuccess) {
                            var listComment = [];
                            $(result.comments).each(function(index, item) {
                                listComment[index] = new Comment(item.id, item.username, item.userImage, item.content, item.createdDate, item.like,item.isLiked,item.isReported,item.isAuthorized);
                            });
                            viewmodel.commentCollection(listComment);
                            viewmodel.commentPageNo(viewmodel.commentPageNo() + 1);
                            viewmodel.isShowPrevBtn(viewmodel.commentPageNo() > 1);
                            viewmodel.isShowNextBtn(viewmodel.commentPageNo() < viewmodel.totalCommentPage());
                        } else {
                            alert(result.message);
                        }
                    }
                });
        },
        fetchPreviousCommentPage: function() {
            $.ajax({
                    url: '@Url.Action("FetchNextCommentPage", "ChapterComments")',
                    type: 'POST',
                    data: ko.toJSON({ chapterId: chapterId, pageNumber: viewmodel.commentPageNo() - 1 }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.isSuccess) {
                            var listComment = [];
                            $(result.comments).each(function(index, item) {
                              listComment[index] = new Comment(item.id, item.username, item.userImage, item.content, item.createdDate, item.like,item.isLiked,item.isReported,item.isAuthorized);
                            });
                            viewmodel.commentCollection(listComment);
                            viewmodel.commentPageNo(viewmodel.commentPageNo() - 1);
                            viewmodel.isShowPrevBtn(viewmodel.commentPageNo() > 1);
                            viewmodel.isShowNextBtn(viewmodel.commentPageNo() < viewmodel.totalCommentPage());
                        } else {
                            alert(result.message);
                        }
                    }
                });
        },
        postComment: function() {
            $.ajax({
                    url: '@Url.Action("Create", "ChapterComments")',
                    type: 'POST',
                    data: ko.toJSON({ content: viewmodel.comment().content(), chapterId: chapterId }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.success) {
                            var addedComment = new Comment(
                                parseInt(result.id),
                                result.userName,
                                result.userImage,
                                viewmodel.comment().content(),
                                result.createdDate,
                                0,
                                false,false,true);
                            viewmodel.commentCollection.unshift(addedComment);
                            viewmodel.comment(new Comment());
                            viewmodel.numberOfComments(viewmodel.numberOfComments() + 1);
                        } else {
                            alert(result.message);
                        }
                    }
                });
        },
         deleteChapter: function() {
                     var answer = confirm("Do you want to delete this chapter?");
               
                     if (answer) {
                         $.ajax({
                                 url: '@Url.Action("DeleteConfirmed", "Chapters")',
                                 type: "POST",
                                 data: JSON.stringify({ id: @Model.Id }),
                                 dataType: "JSON",
                                 contentType: "APPLICATION/JSON; CHARSET=UTF-8",
                                 complete: function() {
                                     window.location = '@Url.Action("Details", "Books", new { id = @Model.BookId })';
                                 },
                                 error: function() {
                                     alert("error ");
                                 }
                             });
                     }
                 },
        cancelPostComment: function() {
            viewmodel.comment(new Comment());
        },
        pictureCollection: ko.observableArray($(pictureList).slice(0,2)),
        availableTagModes: ko.observableArray(availableTagModes),
        selectedTagMode: ko.observable(availableTagModes[0]),
        chapterTemplateName: function() {
            return viewmodel.selectedTagMode().value();
        },
        contentTagCollection: ko.observableArray(contentTagList),
        numberOfLikes: ko.observable( @Model.NumberOfLikes ),
        isReported: ko.observable( @Model.IsReported.BooleanToJavascript() ),
        toggleSidebar: function() {
            $('#sideBar').slideToggle('slow');
            $('#button-toggle').toggleClass("active");
        },
        likeChapter: function() {
            if (!viewmodel.isLiked()) {
                $.ajax({
                        url: '@Url.Action("Like", "Chapters")',
                        type: 'POST',
                        data: ko.toJSON({ chapterId: @Model.Id }),
                        contentType: 'APPLICATION/JSON',
                        success: function(result) {
                            if (result.success) {
                                viewmodel.numberOfLikes(parseInt(viewmodel.numberOfLikes()) + 1);
                                viewmodel.isLiked(!viewmodel.isLiked());
                            }
                        }
                    });
            } else {
                $.ajax({
                        url: '@Url.Action("UnLike", "Chapters")',
                        type: 'POST',
                        data: ko.toJSON({ chapterId: @Model.Id }),
                        contentType: 'APPLICATION/JSON',
                        success: function(result) {
                            if (result.success) {
                                viewmodel.numberOfLikes(parseInt(viewmodel.numberOfLikes()) - 1);
                                viewmodel.isLiked(!viewmodel.isLiked());
                            }
                        }
                    });
            }
        }
    };
ko.applyBindings(viewmodel);
</script>
